var api = require('../config/api.js');
var app = getApp();

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
 */
function formatTime2(date, format) {
  if (date == 'Invalid Date') {
    return '无';
  }

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}

function getFormatTime(date, format, {
  y,
  m,
  d,
  h
} = {}) {
  if (date == 'Invalid Date') {
    return '无';
  }
  y = y ? y : 0;
  m = m ? m : 0;
  d = d ? d : 0;
  h = h ? h : 0;

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
  returnArr.push(date.getFullYear() + y);
  returnArr.push(formatNumber(date.getMonth() + 1 + m));
  returnArr.push(formatNumber(date.getDate() + d));

  returnArr.push(formatNumber(date.getHours() + h));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function (res) {

        if (res.statusCode == 200) {

          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('shopInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/auth/login/login'
            });
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}

function upload(file, callback, callback2) {
  var that = this;
  const uploadTask = wx.uploadFile({
    url: api.StorageUpload,
    filePath: file.url,
    name: 'file',
    success: function (res) {
      // console.log(res)
      var _res = JSON.parse(res.data);
      if (_res.errno === 0) {
        callback(_res);
      }
      if (callback2) {
        callback2();
      }
    },
    fail: function (e) {
      if (callback2) {
        callback2();
      }
      wx.showModal({
        title: '错误',
        content: '上传失败',
        showCancel: false
      })
    },
  })

  uploadTask.onProgressUpdate((res) => {
    console.log('上传进度', res.progress)
    console.log('已经上传的数据长度', res.totalBytesSent)
    console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
  })

}

function getQualificationsInfo(callback) {
  request(api.QualificationsMyInfo).then(function (res) {
    if (res.errno === 0) {
      let user = res.data.userVo || null;
      wx.setStorageSync('shopInfo', user);
      callback(user);
    } else {
      callback(false);
    }
  });
}

function getDateDiff(startTime, endTime, diffType) {
  //将计算间隔类性字符转换为小写
  diffType = diffType.toLowerCase();
  var sTime = new Date(startTime); //开始时间
  var eTime = new Date(endTime); //结束时间
  //作为除数的数字
  var divNum = 1;
  switch (diffType) {
    case "second":
      divNum = 1000;
      break;
    case "minute":
      divNum = 1000 * 60;
      break;
    case "hour":
      divNum = 1000 * 3600;
      break;
    case "day":
      divNum = 1000 * 3600 * 24;
      break;
    default:
      break;
  }
  return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
}

function toDecimal(x, num = 2) {
  var f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(x * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + num) {
    s += '0';
  }
  return s;
}

module.exports = {
  formatTime,
  formatTime2,
  getFormatTime,
  request,
  redirect,
  showErrorToast,
  upload,
  getQualificationsInfo,
  getDateDiff,
  toDecimal
}